package com.quanyan.ic.protocol.client.handler;

import com.quanyan.ic.protocol.Code;
import com.quanyan.ic.protocol.MessageType;
import com.quanyan.ic.protocol.codec.protobuf.ICMessageProto;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by zhuo.shi on 2017/6/1.
 */
public class HandShakeReqHandler extends ChannelInboundHandlerAdapter {

    private static Logger logger = LoggerFactory.getLogger(HandShakeReqHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(buildHandShakeMsg()); //发送握手消息
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        ICMessageProto.ICMessage icMessage = (ICMessageProto.ICMessage) msg;
        if (icMessage.getHeader() != null && icMessage.getHeader().getType() == MessageType.HANDSHAKE_RESP.value()) {
            logger.info("client received handshake msg: {}", icMessage);
            if (icMessage.getHeader().getRespCode() == Code.RC_200.value()) {
                logger.info("handshake success");
                ctx.fireChannelRead(msg);
            } else {
                logger.error("handshake failed");
                ctx.close();
            }
        } else if (icMessage.getHeader() != null && icMessage.getHeader().getType() == MessageType.HEARTBEAT_RESP.value()) {
            //心跳消息
        } else {
            logger.info("client received msg: {}", icMessage);
            ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.fireExceptionCaught(cause);
    }

    /**
     * 构造握手消息
     */
    private ICMessageProto.ICMessage buildHandShakeMsg() {
        ICMessageProto.ICMessage.Builder builder = ICMessageProto.ICMessage.newBuilder();
        ICMessageProto.ICMessage.Header.Builder header = ICMessageProto.ICMessage.Header.newBuilder();
        header.setProtocolVersion(0xAF1);
        header.setType(MessageType.HANDSHAKE_REQ.value());
        header.setPid(34080);
        builder.setHeader(header.build());

        return builder.build();
    }
}
